//
//  ImageCell.m
//  RunloopTableViewDemo
//
//  Created by Jack on 2021/6/30.
//

#import "ImageCell.h"
#import "JKLogManager.h"
#import "DemoCacheManager.h"

@implementation ImageCell{
    UILabel *_coverImageView;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        _coverImageView = [[UILabel alloc] initWithFrame:CGRectZero];
        _coverImageView.textColor = [UIColor whiteColor];
        _coverImageView.backgroundColor = [UIColor lightGrayColor];
        [self.contentView addSubview:_coverImageView];
    }
    return self;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    _coverImageView.frame = CGRectMake(10, 10, self.contentView.bounds.size.width - 20, self.contentView.bounds.size.height - 20);
}

- (void)prepareForReuse{
    [super prepareForReuse];
    _coverImageView.backgroundColor = [UIColor lightGrayColor];
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}


#pragma mark - Private
- (void)ic_changeCover:(NSString *)title{
    _coverImageView.backgroundColor = [UIColor blueColor];
    [[DemoCacheManager sharedManager] cacheResultWithKey:title];;
    [[JKLogManager sharedManager] addLog:title];
}

- (void)useCache{
    _coverImageView.backgroundColor = [UIColor blueColor];
}

#pragma mark - Public
- (void)requestLayoutWithTitle:(NSString *)title isScrolling:(BOOL)scrolling{
    if (title && [title isKindOfClass:[NSString class]] && title.length > 0) {
        _coverImageView.text = title;
        if ([[DemoCacheManager sharedManager] isCachedWithKey:title]) {
            [self useCache];
        }else{
            if (!scrolling) {
                /**
                 直接使用runloop等到结束后加载图片的效果并不好，因为在停止滑动时还是有限加载了滑动过程中错过的cell
                 */
                [self performSelector:@selector(ic_changeCover:) withObject:title afterDelay:0 inModes: @[NSDefaultRunLoopMode]];
            }
        }
    }
}

@end
